#!/usr/bin/env bash

LOG_NAME="log.log"
LOG_ROTATE_SIZE=32

# log_init LOG_NAME LOG_ROTATE_SIZE
function log_init {
    mkdir -p ${LOG_DIR}
    LOG_NAME=$1
    if [[ ! -z $2 ]]; then
        LOG_ROTATE=$2
    fi
}

# could be shorter according to http://stackoverflow.com/questions/5789526/log-rotating-with-a-bash-script
function log_rotate {
    local log=$1

    if [ -f ${log} ] ; then
        CNT=5
        let P_CNT=CNT-1
        if [ -f ${log}.5 ] ; then
            rm -f ${log}.5
        fi

        # Renames logs .1 trough .4
        while [[ ${CNT} -ne 1 ]] ; do
            echo "while ${CNT} -ne 1"
            if [ -f ${log}.${P_CNT} ] ; then
              mv ${log}.${P_CNT} ${log}.${CNT}
            fi
            let CNT=CNT-1
            let P_CNT=P_CNT-1
        done

        # Renames current log to .1
        mv ${log} ${log}.1
        echo "" > ${log}
    fi
}

function log_rotate_by_size {
    file_size=$(du -m ${LOG_DIR}/${LOG_NAME} | cut -f1)
    if [[ ${file_size} -gt ${LOG_ROTATE_SIZE} ]]; then
        log_rotate ${LOG_DIR}/${LOG_NAME}
    fi
}

function log_this {
    echo "$(date "+%Y-%m-%d %H:%M:%S")" $@
    echo "$(date "+%Y-%m-%d %H:%M:%S")" $@ >> ${LOG_DIR}/${LOG_NAME}
}

function log_debug {
    echo "$(date "+%Y-%m-%d %H:%M:%S")" "[DBG]" $@
    echo "$(date "+%Y-%m-%d %H:%M:%S")" "[DBG]" $@ >> ${LOG_DIR}/${LOG_NAME}
}

function log_info {
    echo "$(date "+%Y-%m-%d %H:%M:%S")" "[INF]" $@
    echo "$(date "+%Y-%m-%d %H:%M:%S")" "[INF]" $@ >> ${LOG_DIR}/${LOG_NAME}
}

function log_error {
    echo "$(date "+%Y-%m-%d %H:%M:%S")" "[ERR]" $@
    echo "$(date "+%Y-%m-%d %H:%M:%S")" "[ERR]" $@ >> ${LOG_DIR}/${LOG_NAME}
}